﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoMapper;

namespace UserGroupData
{
    public class PrizeRepository : IPrizeRepository
    {
        public PrizeDTO GetPrize(int id)
        {
            using (var ctx = new UserGroupEntities())
            {
                var meeting = ctx.Prizes.Where(d => d.Id == id);
                var entity = meeting.FirstOrDefault();
                Mapper.CreateMap<Prize, PrizeDTO>();
                var dto = Mapper.Map<Prize, PrizeDTO>(entity);
                return dto;
            }
        }

        public List<PrizeDTO> GetAllPrizes()
        {
            using (var ctx = new UserGroupEntities())
            {
                var entities = ctx.Prizes.ToList();
                Mapper.CreateMap<Prize, PrizeDTO>();
                var dto = Mapper.Map<List<Prize>, List<PrizeDTO>>(entities);
                return dto;
            }
        }

        public int AddNewPrize(PrizeDTO dto)
        {
            using (var ctx = new UserGroupEntities())
            {
                Mapper.CreateMap<PrizeDTO, Prize>();
                var entity = Mapper.Map<PrizeDTO, Prize>(dto);
                ctx.AddToPrizes(entity);
                ctx.SaveChanges();

                Prize newEntity = ctx.Prizes.Where(
                    d => d.Name == entity.Name).FirstOrDefault();

                if (newEntity == null)
                    return -1;
                else
                    return newEntity.Id;
            }
        }

        public void UpdatePrize(PrizeDTO dto)
        {
            using (var ctx = new UserGroupEntities())
            {
                Mapper.CreateMap<PrizeDTO, Prize>();
                var entity = Mapper.Map<PrizeDTO, Prize>(dto);
                ctx.ApplyCurrentValues("Prizes", entity);
                ctx.SaveChanges();
            }
        }

        public void DeletePrizeDTO(int id)
        {
            using (var ctx = new UserGroupEntities())
            {
                Prize dbDept = ctx.Prizes.First(d => d.Id == id);
                ctx.DeleteObject(dbDept);
                ctx.SaveChanges();
            }
        }
    }
}
